from django.shortcuts import render
from utils.views import LoginRequiredJsonMixin
from django.http import JsonResponse, HttpResponseBadRequest
from django_redis import get_redis_connection
import json
from apps.goods.utils import get_breadcrumb
from django.views import View
from apps.goods.models import SKU, GoodsCategory, GoodsVisitCount
from django.core.paginator import Paginator, EmptyPage
# Create your views here.
from haystack.views import SearchView
from django.http import JsonResponse
from utils.goods import get_goods_specs, get_categories
from datetime import date
from apps.goods.models import GoodsVisitCount






class UserLookView(LoginRequiredJsonMixin, View):
    '''用户浏览记录'''
    def get(self, request):
        # 拿到redis数据
        redis_conn = get_redis_connection('history')
        skus = redis_conn.lrange('history_%s' % request.user.id, 0, -1)

        # 遍历数据
        lists = []
        for sku_id in skus:
            # 查询数据库
            sku = SKU.objects.get(id=sku_id)
            lists.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'skus': lists})


    def post(self, request):
        # 拿到sku_id
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        user_id = request.user.id

        # 以列表的方式存redis
        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()
        # 去重
        pl.lrem('history_%s' % user_id, 0, sku_id)

        # 保存
        pl.lpush('history_%s' % user_id, sku_id)
        # 截取
        pl.ltrim('history_%s' % user_id, 0, 4)
        # 执行
        pl.execute()



        # 响应结果
        return JsonResponse({'code': 0, 'errmsg': 'OK'})






# ========================================================================================================
class ShopCountView(LoginRequiredJsonMixin, View):
    '''商品访问量'''
    def post(self, request, category_id):
        # 拿到category_id查询对应的商品
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # 获取当天日期
        today_date = date.today()

        try:
            count_data = category.goodsvisitcount_set.get(date=today_date)

        except:
            count_data = GoodsVisitCount()

        try:
            count_data.count += 1
            count_data.category = category
            count_data.save()

        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '新增失败'})
        return JsonResponse({'code': 0, 'errmsg': 'OK'})

# ====================================================================================================
class DetailView(View):
    """商品详情页"""
    def get(self, request, sku_id):
        """提供商品详情页"""
        # 获取当前sku的信息
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

        # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)

        # 渲染页面
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
        }
        return render(request, 'detail.html', context)



# ==========================================================================================================
# 搜索引擎
class MySearchView(SearchView):
    '''重写SearchView类'''
    def create_response(self):
        page = self.request.GET.get('page')
        # 获取搜索结果
        context = self.get_context()
        data_list = []
        for sku in context['page'].object_list:
            data_list.append({
                'id':sku.object.id,
                'name':sku.object.name,
                'price':sku.object.price,
                'default_image_url':sku.object.default_image.url,
                'searchkey':context.get('query'),
                'page_size':context['page'].paginator.num_pages,
                'count':context['page'].paginator.count
            })
        # 拼接参数, 返回
        return JsonResponse(data_list, safe=False)


# ==========================================================================================================
# 商品列表
class ShopHotView(View):
    def get(self, request, category_id):
        # 通过category_id查询参数
        try:
            skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[0:2]
        except SKU.DoesNotExist:
            return HttpResponseBadRequest('数据查询错误')

        lists = []
        for sku in skus:
            lists.append({
                "id": sku.id,
                "default_image_url": sku.default_image.url,
                "name": sku.name,
                "price": sku.price,
            })
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'hot_skus': lists})


# ===================================================================================================

class ShopListView(View):
    '''展示商品列表页'''
    def get(self, request, category_id):
        # 拿到参数

        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')
        # 用category_id查询数据
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return HttpResponseBadRequest('数据库查询错误')

        # 生成面包屑数据
        breadcrumb = get_breadcrumb(category)

        # 查询商品排序
        try:
            skus = SKU.objects.filter(category=category, is_launched=True).order_by(ordering)
        except SKU.DoesNotExist:
            return HttpResponseBadRequest('数据查询失败')


        # 生成分页数据
        paginator = Paginator(skus, page_size)
        # 获取商品数据
        try:
            page_skus = paginator.page(page)
        except EmptyPage:
            return JsonResponse({'code': 400,
                                 'errmsg': 'page数据出错'})

        list = []
        # 整理格式:
        for sku in page_skus:
            list.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })

        # 获得列表总页数
        total_page = paginator.num_pages
        # 把数据变为 json 发送给前端
        return JsonResponse({
                             'code': 0,
                             'errmsg': 'ok',
                             'breadcrumb': breadcrumb,
                             'list': list,
                             'count': total_page
                            })
